package com.example.test.config.aop;


import cn.hutool.core.util.HashUtil;
import cn.hutool.json.JSONUtil;
import com.example.test.Controller;
import com.example.test.param.CheckParam;
import com.example.test.param.DataPerm;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 重复提交校验处理切面
 *
 * @author tyd
 * @date 2021/2/1
 */
@Aspect
@Component
@Slf4j
public class DataPermAspect implements ApplicationContextAware {



    @Pointcut("@annotation(com.example.test.param.DataPerm)")
    public void dataPerm() {
    }

    private ApplicationContext applicationContext;

    /**
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before(value = "dataPerm()")
    public void checkDataPerm(JoinPoint joinPoint) throws Throwable {
        Signature signature= joinPoint.getSignature();
        if(!(signature instanceof MethodSignature)){
            return;
        }
        MethodSignature methodSignature=(MethodSignature)signature;
        Method method=methodSignature.getMethod();
        DataPerm annotation = method.getAnnotation(DataPerm.class);
        Class<? extends CheckParam> aClass = annotation.checkBean();
        boolean update = annotation.update();
        //参数
        Object[] args=joinPoint.getArgs();
        //参数名
        String[] params=new DefaultParameterNameDiscoverer().getParameterNames(method);

        CheckParam checkParam = applicationContext.getBean(aClass);
        for (Object arg : args) {
            checkParam.checkParam(JSONUtil.toJsonStr(arg), update);
        }
    }



    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}
